package com.zimmur.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.zimmur.common.PropertiesCommon;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.controller.BaseController;
import com.zimmur.tenpay.util.MD5;
import com.zimmur.tools.JsonEntity;
import com.zimmur.tools.MD5Util;

public class RequestApiInterceptor extends HandlerInterceptorAdapter {
	private Logger log = LoggerFactory.getLogger(RequestApiInterceptor.class);
	private final static String APIPUBLICKEY="api.publicKey";
	private final static String Charset = "utf-8";
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8"); 		
		JsonEntity entity = new JsonEntity(StatusCodeEnum.APICODE100402);
		//时间戳验证
        String timestamp = request.getHeader("timestamp");
        if(StringUtils.isEmpty(timestamp)){        	
        	response.getWriter().write(JSON.toJSONString(entity));
        	return false;
        }
        try {
        	long requestTime = Long.parseLong(timestamp);
	        long curTime = System.currentTimeMillis();
	        if((curTime - requestTime) > 10 * 60 * 1000){
	        	response.getWriter().write(JSON.toJSONString(entity));
	            return false;
	        }
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			response.getWriter().write(JSON.toJSONString(entity));
		}
        entity = new JsonEntity(StatusCodeEnum.APICODE100403);
        String publickey=PropertiesCommon.getProperty(APIPUBLICKEY);
        String sign=request.getHeader("sign");
        String token_md5=MD5Util.MD5Encode(publickey, Charset);
        token_md5=MD5Util.MD5Encode(token_md5, Charset).toUpperCase();
        if(!token_md5.equals(sign)){
        	response.getWriter().write(JSON.toJSONString(entity));
        	return false;
        }
		BaseController.setRequest(request);
		BaseController.setResponse(response);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) throws Exception {
		BaseController.removeRequest();
		BaseController.removeResponse();
	}
}
